package com.redwine.app;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.redwine.app.utils.Constants;
import com.redwine.app.utils.ErrorResponseException;
import com.redwine.app.utils.FileUtils;
import com.redwine.app.utils.ImageUtils;
import com.redwine.app.utils.LogUtil;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.utils.ShowDialogUtils;
import com.redwine.app.utils.Utils;
import com.redwine.app.utils.luban.Luban;
import com.redwine.app.utils.luban.OnCompressListener;
import com.redwine.app.view.EmptyView;
import com.redwine.app.view.SwipeBackLayout;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class BaseActivity extends FragmentActivity implements View.OnClickListener {
    //    public static RequestQueue mQueue;
    // 主体显示
    protected ViewGroup mainBody;
    protected SwipeBackLayout layout;

    private ProgressDialog mProgressDialog;

    public TextView text_country;

    // 是否使用模板 true 使用模板，false 不使用模板
    protected boolean isTemplate = false;

    public final static int REQUEST_CAMERA = 1;
    private static final int PICK_PHOTO = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //        //        实现全屏
        //        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        //        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        //StatusBarCompat.setColor(this, 0xb4000000, 80);//4.3新加时间栏半透明
        //layout = (SwipeBackLayout) LayoutInflater.from(this).inflate(
        //        R.layout.right_finish, null);
        //layout.attachToActivity(this);
        //        mQueue = Volley.newRequestQueue(getApplicationContext());
        ViewUtils.inject(this);
        mainBody = (ViewGroup) findViewById(R.id.view_mainBody);

    }

    @Override
    public void setContentView(int layoutResID) {
        if (layoutResID == R.layout.activity_base) {
            super.setContentView(layoutResID);
        } else {
            mainBody.removeAllViews();
            mainBody.addView(this.getLayoutInflater()
                    .inflate(layoutResID, null));
        }
    }

    @Override
    public void setContentView(View view) {
        mainBody.removeAllViews();
        mainBody.addView(view);
    }

    protected ErrorListener mErrorListener = new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Throwable t = error.getCause();
            if (t instanceof ErrorResponseException) {
                //                Log.e("params", "message" + error.getMessage().toString());
                Utils.showToast(error.getMessage());
            } else {
                if (!NetUtil.checkNet(BaseActivity.this)) {
                    Utils.showToast(R.string.generic_check);
                } else {
                    //                    Utils.showToast(R.string.generic_check_online);
                }
            }
        }
    };

    public void updateWebViewSettings(WebView web) {
        WebSettings webSettings = web.getSettings();
        Log.e("webview", "webSettings" + webSettings);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        Utils.setDefaultWebSettings(web);
    }

    public void webviewSetContent(WebView web, String content) {
        web.loadData(content, "text/html; charset=UTF-8", null);
    }


    // Press the back button in mobile phone
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, R.anim.base_slide_right_out);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);       //统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public String countryCode = "86";//不同国家的国家代码\
    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            LogUtil.i("qcl 接收到的广播：", action);
            if (action.equals(Constants.INTENT_CHOSE_COUNTRY)) {
                countryCode = intent.getStringExtra("country_code");
                String country_name = intent.getStringExtra("country_name");
                text_country.setText(country_name);
            } else if (action.equals(Constants.INTENT_USER_LOGGED_IN)) {
                finish();
                overridePendingTransition(0, R.anim.base_slide_right_out);
            }
        }
    };

    /**
     * 设置更新时间
     */
    protected void setUpdateTime(PullToRefreshListView mListView) {
        String label = DateUtils.formatDateTime(BaseActivity.this,
                System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE
                        | DateUtils.FORMAT_ABBREV_ALL);
        mListView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
    }

    protected void checkNet() {
        if (!NetUtil.checkNet(this)) {
            Utils.showToast(R.string.generic_check);
            return;
        }
    }

    /**
     * 替换finish
     */
    protected void onBackPress() {
        onBackPressed();
    }


    public void showWaiting() {
        if (mProgressDialog == null) {
            mProgressDialog = ShowDialogUtils.loadingDialog(this);
        } else {
            mProgressDialog.show();
        }
    }

    public void showWaiting(String content) {
        if (mProgressDialog == null) {
            mProgressDialog = ShowDialogUtils.loadingDialog(this, content);
        } else {
            mProgressDialog.show();
        }
    }

    public void dismissWaiting() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }


    /**
     * 传递一个，分割的字符串返回一个集合
     *
     * @param content
     * @return
     */
    public List<String> strConvertList(String content) {
        List<String> list = new ArrayList<>();
        if (!TextUtils.isEmpty(content)) {
            String[] split = content.split(",");
            for (int i = 0; i < split.length; i++) {
                list.add(split[i]);
            }
            return list;
        } else {
            return new ArrayList<>();
        }
    }


    private Dialog choosePhotoDialog;

    /**
     * 选择相册的弹出框
     */
    public void choosePhotoDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_choose_photo, null);
        Button photoAlbum = (Button) view.findViewById(R.id.open_photo_album);
        Button takingPictures = (Button) view.findViewById(R.id.open_taking_pictures);
        Button cancel = (Button) view.findViewById(R.id.cancel);
        photoAlbum.setOnClickListener(this);
        takingPictures.setOnClickListener(this);
        cancel.setOnClickListener(this);
        choosePhotoDialog = new Dialog(this, R.style.AppBaseTheme);
        choosePhotoDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = choosePhotoDialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.MATCH_PARENT;
        choosePhotoDialog.onWindowAttributesChanged(wl);
        choosePhotoDialog.setCanceledOnTouchOutside(true);
        choosePhotoDialog.show();
    }

    /**
     * 关闭相册的弹出框
     */
    public void dismissChoosePhotoDialog() {
        if (null != choosePhotoDialog && choosePhotoDialog.isShowing())
            choosePhotoDialog.dismiss();
    }

    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
                return;
            } else {
                ImageUtils.takeOrChoosePhoto(this, REQUEST_CAMERA);
            }
        } else {
            ImageUtils.takeOrChoosePhoto(this, REQUEST_CAMERA);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        // 相机拍照完成后，返回图片路径 打开剪裁页面
        if (requestCode == REQUEST_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                String photoFromResultStr = ImageUtils.getPhotoFromResultStr(this, true, data);
                if (!TextUtils.isEmpty(photoFromResultStr))
                    setCompressedImage(photoFromResultStr);
            }
        } else if (requestCode == PICK_PHOTO) {//相册选择完成后，返回图片路径 打开剪裁页面
            String photoFromResultStr = ImageUtils.getPhotoFromResultStr(this, false, data);
            if (!TextUtils.isEmpty(photoFromResultStr))
                setCompressedImage(photoFromResultStr);
        }
    }

    private void setCompressedImage(String path) {
        Luban.with(this)
                .load(path)
                .ignoreBy(100)
                .setTargetDir(FileUtils.getImagePath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        photoCallBack(file.getAbsolutePath());
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }

    /**
     * 拍照和图库的回调
     */
    protected void photoCallBack(String path) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                dismissChoosePhotoDialog();
                break;

            case R.id.open_photo_album:
                //打开相册
                dismissChoosePhotoDialog();
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PICK_PHOTO);
                break;

            case R.id.open_taking_pictures:
                //拍照
                dismissChoosePhotoDialog();
                checkCameraPermission();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        UMShareAPI.get(this).release();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        super.onDestroy();
    }

    public Drawable getIdDrawable(int drawableId) {
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        return drawable;
    }

    public void setForegroundColorSpan(TextView textView, int start, int end, String content) {
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_e82565));
        builder.setSpan(foregroundColorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(builder);
    }

    /**
     * 点击加载错误的回调
     */
    protected void emptyOnclick() {

    }

    /**
     * 设置网络错误展示
     */
    public void setErrorView(EmptyView emptyView, PullToRefreshListView mListView) {
        emptyView.show();
        if (null != mListView)
            mListView.setMode(PullToRefreshBase.Mode.DISABLED);
        emptyView.emptyTopLayout.setVisibility(View.VISIBLE);
        emptyView.emptyErrorBottomImage.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
        emptyView.setEnabled(true);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyOnclick();
            }
        });
    }

    /**
     * 设置empty展示
     */
    public void setEmptyView(EmptyView emptyView, PullToRefreshListView mListView) {
        emptyView.show();
        if (null != mListView)
            mListView.setMode(PullToRefreshBase.Mode.DISABLED);
        emptyView.setVisibility(View.VISIBLE);
        emptyView.emptyTopLayout.setVisibility(View.GONE);
        emptyView.emptyErrorBottomImage.setVisibility(View.VISIBLE);
        emptyView.setEnabled(true);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyOnclick();
            }
        });
    }


    /**
     * 设置隐藏展示的view
     */
    public void setHiddenView(EmptyView emptyView) {
        emptyView.bind();
        emptyView.setVisibility(View.GONE);
        emptyView.emptyTopLayout.setVisibility(View.GONE);
        emptyView.emptyErrorBottomImage.setVisibility(View.VISIBLE);
        emptyView.setEnabled(false);
    }

}
